const router = require("express").Router();
const sql = require("../mysql");
const Customer = require("../mysql/collection/Customer");
const uuid = require("uuid");

/**
 * @api {GET} /admin/crm/customers 获取客户列表
 * @apiName GetCustomers
 * @apiGroup CRM-Customer
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [status] 客户状态筛选
 * @apiParam {String} [source] 客户来源筛选
 * @apiParam {String} [assignedTo] 负责人筛选
 * @apiParam {String} [keyword] 关键词搜索(姓名、公司、电话)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 客户列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/customers", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, status, source, assignedTo, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (status) query.status = status;
    if (source) query.source = source;
    if (assignedTo) query.assignedTo = assignedTo;
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { company: { $regex: keyword, $options: 'i' } },
        { phone: { $regex: keyword, $options: 'i' } }
      ];
    }
    
    const total = await Customer.countDocuments(query);
    const list = await Customer.find(query)
      .populate('assignedTo', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取客户列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取客户列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/customers 创建客户
 * @apiName CreateCustomer
 * @apiGroup CRM-Customer
 *
 * @apiParam {String} name 客户姓名
 * @apiParam {String} [company] 公司名称
 * @apiParam {String} phone 联系电话
 * @apiParam {String} [email] 邮箱地址
 * @apiParam {String} [address] 联系地址
 * @apiParam {Array} [tags] 客户标签
 * @apiParam {String} [source] 客户来源
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 客户数据
 */
router.post("/customers", async (req, res) => {
  try {
    const customerData = {
      ...req.body,
      customerId: "CUS_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase()
    };
    
    // 检查电话号码是否已存在
    const existingCustomer = await Customer.findOne({ phone: customerData.phone });
    if (existingCustomer) {
      return res.send({
        code: "400",
        message: "该电话号码已存在"
      });
    }
    
    const customer = await Customer.create(customerData);
    const populatedCustomer = await Customer.findById(customer._id)
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "创建客户成功",
      data: populatedCustomer
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建客户失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/customers/:id 获取客户详情
 * @apiName GetCustomerDetail
 * @apiGroup CRM-Customer
 *
 * @apiParam {String} id 客户ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 客户详情
 */
router.get("/customers/:id", async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id)
      .populate('assignedTo', 'adminname');
    
    if (!customer) {
      return res.send({
        code: "404",
        message: "客户不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取客户详情成功",
      data: customer
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取客户详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/customers/:id 更新客户信息
 * @apiName UpdateCustomer
 * @apiGroup CRM-Customer
 *
 * @apiParam {String} id 客户ID
 * @apiParam {String} [name] 客户姓名
 * @apiParam {String} [company] 公司名称
 * @apiParam {String} [phone] 联系电话
 * @apiParam {String} [email] 邮箱地址
 * @apiParam {String} [address] 联系地址
 * @apiParam {Array} [tags] 客户标签
 * @apiParam {String} [source] 客户来源
 * @apiParam {String} [status] 客户状态
 * @apiParam {String} [assignedTo] 分配给销售代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的客户数据
 */
router.put("/customers/:id", async (req, res) => {
  try {
    const customer = await Customer.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('assignedTo', 'adminname');
    
    if (!customer) {
      return res.send({
        code: "404",
        message: "客户不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新客户信息成功",
      data: customer
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新客户信息失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/customers/:id 删除客户
 * @apiName DeleteCustomer
 * @apiGroup CRM-Customer
 *
 * @apiParam {String} id 客户ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/customers/:id", async (req, res) => {
  try {
    const customer = await Customer.findByIdAndDelete(req.params.id);
    
    if (!customer) {
      return res.send({
        code: "404",
        message: "客户不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "删除客户成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除客户失败",
      error: error.message
    });
  }
});

module.exports = router;